package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        // 1.从redis查询类型数据
        String typeJson = stringRedisTemplate.opsForValue().get(key);
        // 2.如果有，就直接返回
        if (typeJson != null){
            List<ShopType> list = JSONUtil.toList(typeJson, ShopType.class);
            return Result.ok(list);
        }
        // 3.如果没有就从数据库中查询
        List<ShopType> typeList = query().orderByAsc("sort").list();
        // 4.从数据库中没有查询到数据，就报错
        if (typeList == null || typeList.size() <= 0){
            return Result.fail("暂无数据");
        }
        // 5.查到数据，存入redis
        String jsonStr = JSONUtil.toJsonStr(typeList);
        stringRedisTemplate.opsForValue().set(key, jsonStr, RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);
        // 6.返回
        return Result.ok(typeList);
    }
}
